package excmy

import (
	"errors"
	"github.com/xuri/excelize/v2"
	"regexp"
	"strconv"
	"strings"
)

type Sheet struct {
	Name   string
	File   *excelize.File
	Fields []string
	//字段边界 第0个是左边界位置（如A1），1是右边界
	boundary []string
}

// Field 设置字段名，方便定基，为以后开发做准备，同时确认字段的边界
func (sheet *Sheet) SetField(line int, form, to string) {
	sheet.Fields = sheet.ReadLine(line, form, to)
	boundary := make([]string, 2)
	boundary[0] = form
	boundary[1] = to
	sheet.boundary = boundary
}

func (sheet *Sheet) ReadLine(line int, form, to string) []string {
	result := make([]string, 0)
	FromString := form + int2string(line)
	ToString := to + int2string(line)
	formCell, err := sheet.NewCell(FromString)
	if err != nil {
		panic(err)
	}
	toCell, err := sheet.NewCell(ToString)
	if err != nil {
		panic(err)
	}

	for {
		result = append(result, formCell.Value())
		formCell = formCell.Right()
		if formCell.Location() == toCell.Location() {
			result = append(result, formCell.Value())
			return result
		}
	}

}

func (sheet *Sheet) ReadLineToInterface(line int, form, to string, cellType []string) []interface{} {
	//TODO:未完成！！！！！！
	result := make([]interface{}, 0)
	FromString := form + int2string(line)
	//ToString := to + int2string(line)
	if columnToNumber(to)-columnToNumber(form)+1 != len(cellType) {
		panic("ReadLineToInterface 和cellType长度不一样" + sheet.Name)
	}
	formCell, err := sheet.NewCell(FromString)
	if err != nil {
		panic(err)
	}
	//toCell, err := sheet.NewCell(ToString)
	//if err != nil {
	//	panic(err)
	//}

	for i := 0; i < len(cellType); i++ {
		result = append(result, formCell.ValueInterface(cellType[i]))
		formCell = formCell.Right()
	}
	return result
}

func (sheet *Sheet) NewCell(location string) (*Cell, error) {
	// 使用正则表达式来匹配列和行
	// 假设列由大写字母组成，行由数字组成
	// 允许列在行号之前或之后，但不允许有其他字符或格式错误
	location = strings.ToUpper(location)
	re := regexp.MustCompile(`^([A-Z]+)(\d+)|(\d+)([A-Z]+)$`)
	matches := re.FindStringSubmatch(location)
	if matches == nil {
		return nil, errors.New("invalid location format")
	}

	// 根据匹配结果提取列和行
	var colStr, rowStr string
	if matches[1] != "" { // 列在行之前
		colStr = matches[1]
		rowStr = matches[2]
	} else { // 列在行之后
		colStr = matches[4]
		rowStr = matches[3]
	}

	// 验证并转换行号
	row, err := strconv.ParseUint(rowStr, 10, 32)
	if err != nil {
		return nil, errors.New("invalid row number")
	}

	// 返回Cell实例
	return &Cell{
		Row:    uint(row),
		Column: colStr,
		Sheet:  sheet,
	}, nil
}
